package main

import (
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"
)

var i int
var delayCount int

var lock sync.Mutex

func main() {
	http.HandleFunc("/", indexHandle)
	err := http.ListenAndServe(":2021", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func indexHandle(w http.ResponseWriter, r *http.Request) {
	lock.Lock()
	i++
	lock.Unlock()

	fmt.Printf("第%d次！\n", i)
	if i%5 == 0 {
		delayCount = 3
		fmt.Println("我是一个慢响应")
		//每2倍，模拟一个3秒钟的慢响应,并且连续3次都是慢响应
		time.Sleep(time.Second * 3)
		w.Write([]byte("Hello,I'm very slow! \n"))
		return
	}

	if delayCount > 0 {
		fmt.Println("我是一个慢响应的延迟慢响应")
		time.Sleep(time.Second * 3)
		w.Write([]byte("Hello,I'm very slow! \n"))
		delayCount--
		return
	}

	w.Write([]byte("Hello,I'm index handle! \n"))
}
